package com.zzyl.intercept;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

@Component
public class UserInterceptor implements HandlerInterceptor {
// 注入密钥
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) throws Exception {
        // 1.某些请求需要放行
        // 如果不是映射到方法就放行，比如跨域验证请求，静态资源不需要身份校验：只拦截Controller类的方法
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        // 2.获取请求头的令牌
      String token=  request.getHeader(Constants.USER_TOKEN);

        if(StrUtil.isEmpty(token)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        // 3.校验令牌
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        // 获取token
        if (ObjectUtil.isEmpty(claims)) { // 没有令牌，没有权限继续
            //token失效
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        // 获取令牌中的用户id
        Integer userId = (Integer) claims.get(Constants.JWT_USERID);
        if(userId==null){ // 如果用户id不存在，则token可能为假冒token
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        UserThreadLocal.set(Long.valueOf(userId.toString())); // 通过拦截器中，每次都调用线程池存入用户id
        //4.校验成功，放行
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
        //LocalDateTime localDateTime = LocalDateTimeUtil.of(1000l);//
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
